package com.example.demo.service;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.test.Test;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserService {

    //用于自动装配bean对象
    @Autowired
    private UserMapper userMapper;

    public List<User> findAll(){
        return  userMapper.findAll();

    }

    public List<User> findAge(){
        return  userMapper.findAge(16);

    }

    public void  packJson( HttpServletResponse response){
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("lin","1");
        String name = "test";
        //打包成.json文件
        try (OutputStream outputStream = response.getOutputStream()
        ) {
            JSONObject object = new JSONObject(hashMap);
            String jsonStr = object.toString();
            byte[] bytes = jsonStr.getBytes(StandardCharsets.UTF_8);
            // 全文件类型（传什么文件返回什么文件流）
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + name + ".json" + "\"");
            response.setHeader("Accept-Ranges", "bytes");
            outputStream.write(bytes);
            // 将缓存区数据进行输出
            outputStream.flush();
        } catch (IOException e) {
            log.error("unpack error : ", e);
        }

    }

}
